﻿using Dsl.Ped.Common.Exceptions;

namespace Dsl.Ped.Common.Helpers
{
    /// <summary>
    /// Helper for the XAML handling
    /// </summary>
    public class XamlHelper
    {
        /// <summary>
        /// Check if the name is valid xaml name in accordance to xaml grammar
        /// http://msdn.microsoft.com/en-us/library/ms742534(v=vs.90).aspx
        /// </summary>
        /// <param name="name">Name to be validated</param>
        /// <returns>Name if it is valid, throws exception otherwise</returns>
        /// <exception cref="InvalidStringException">Exception thrown when the name is invalid</exception>
        public static string CheckValidXamlName(string name)
        {
            // Check if the name is not empty
            if (name == null)
            {
                throw new InvalidStringException(name, "Must not be null");
            }

            // Empty string is allowed
            if (name == string.Empty)
            {
                return name;
            }

            // Check if the name starts with letter or underscore
            if (!char.IsLetter(name[0]) && !name.StartsWith("_"))
            {
                throw new InvalidStringException(name, "Must start with a letter or underscore");
            }

            // Check if other characters are letter, digits or underscores
            if (name.Length > 1)
            {
                for (int i = 1; i < name.Length; i++)
                {
                    if (char.IsLetterOrDigit(name[i]) || name[i] == '_')
                    {
                        continue;
                    }
                    else
                    {
                        throw new InvalidStringException(name, string.Format("Forbidden character '{0}' on a position {1}. Use letter, digit or underscore instead", name[i], i));
                    }
                }
            }

            return name;
        }
    }
}
